<template>
  <XenListPage
    title="待办中心"
    :dataList="todoList"
    :visibleFields="visibleFields"
    :filterFields="filterFields"
    :actions="actions"
    :themeConfig="themeConfig"
    :loading="loading"
    :enableAutoRefresh="false"
    :enableSilentRefresh="true"
    :silentRefreshFn="silentRefreshFn"
    :initialFilterValues="filterForm"
    searchPlaceholder="点击筛选待办事项"
    emptyText="暂无待办事项"
    emptyDesc="暂时没有收到任何待办事项"
    createPagePath="/subpkg-todocenter/create"
    detailPagePath="/subpkg-todocenter/details"
    editPagePath="/subpkg-todocenter/edit"
    permission-module="systodocenter"
    :show-add-button="false"
    :show-delete-button="false"
    :show-edit-button="false"
    @delete="handleDelete"
    @filter="handleFilter"
    @refresh="handleRefresh"
    @silent-refresh="handleSilentRefresh"
    @view="handleView"
  >
    <!-- 自定义插槽图标 -->
    <template #search-icon>
      <uni-icons type="search" size="18" color="#999"></uni-icons>
    </template>
    <template #add-icon>
      <uni-icons type="plus" size="18" color="#ffffff"></uni-icons>
    </template>
    <template #loading-icon>
      <uni-icons type="spinner-cycle" size="24" color="#666"></uni-icons>
    </template>
    <template #empty-icon>
      <uni-icons type="info" size="48" color="#ccc"></uni-icons>
    </template>
    <template #action-icon-delete>
      <uni-icons type="trash" size="16" color="#FF5252"></uni-icons>
    </template>
    <template #action-icon-edit>
      <uni-icons type="compose" size="16" color="#4CAF50"></uni-icons>
    </template>
    <template #action-icon-view>
      <uni-icons type="eye" size="16" color="#7881de"></uni-icons>
    </template>
  </XenListPage>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import XenListPage from "@/layouts/XenListPage.vue";
import SystodocenterApi from "./api/index";
import type { ISysTodoCenterView, ISysTodoCenterQuery } from "./api/interface";

// 创建API实例
const api = SystodocenterApi();

// 主题配置
const themeConfig = {
  primaryColor: "#7881de",
  secondaryColor: "#764ba2",
  gradientStart: "#667eea",
  gradientEnd: "#764ba2",
};

// 定义列表显示字段（根据ISysTodoCenterView接口）
// 按要求顺序显示：标题、单据编号、业务类型、状态、优先级、创建时间
const visibleFields = [
  { key: "Title", label: "标题" },
  { key: "BillCode", label: "单据编号" },
  { key: "BusinessType", label: "业务类型" },
  {
    key: "Status",
    label: "状态",
    type: "badge",
    formatter: (value: any) => {
      const statusMap: Record<string, string> = {
        待办: "待办",
        已办: "已办",
        已协同: "已协同",
        我的提交: "我的提交",
      };
      return statusMap[value || ""] || "未知状态";
    },
    badgeConfig: {
      colorMap: {
        待办: "orange",
        已办: "green",
        已协同: "blue",
        我的提交: "purple",
      } as Record<string, string>,
      defaultColor: "gray",
      prefix: "badge-",
    },
  },
  {
    key: "Priority",
    label: "优先级",
    type: "badge",
    formatter: (value: any) => {
      const priorityMap: Record<string, string> = {
        低: "低",
        普通: "普通",
        高: "高",
        紧急: "紧急",
      };
      return priorityMap[value || ""] || "普通";
    },
    badgeConfig: {
      colorMap: {
        低: "gray",
        普通: "cyan",
        高: "yellow",
        紧急: "red",
      } as Record<string, string>,
      defaultColor: "cyan",
      prefix: "badge-",
    },
  },
  {
    key: "CreateTime",
    label: "创建时间",
    formatter: (value: any) => {
      if (!value) return "";
      const date = new Date(value);
      return date.toLocaleDateString() + " " + date.toLocaleTimeString();
    },
  },
];

// 定义搜索筛选字段（根据ISysTodoCenterQuery接口）
// 包含：单据编号、业务类型、状态、优先级
const filterFields = [
  { key: "billCode", label: "单据编号", placeholder: "请输入单据编号" },
  { key: "businessType", label: "业务类型", placeholder: "请输入业务类型" },
  {
    key: "status",
    label: "状态",
    type: "selector",
    placeholder: "请选择状态",
    options: ["待办", "已办", "已协同", "我的提交"],
  },
  {
    key: "priority",
    label: "优先级",
    type: "selector",
    placeholder: "请选择优先级",
    options: ["低", "普通", "高", "紧急"],
  },
];

// 定义操作按钮
const actions = [
  {
    key: "delete",
    label: "删除",
    icon: "trash",
    color: "#FF5252",
    class: "delete-btn",
  },
  {
    key: "edit",
    label: "编辑",
    icon: "compose",
    color: "#4CAF50",
    class: "edit-btn",
  },
  {
    key: "view",
    label: "查看",
    icon: "eye",
    color: "#7881de",
    class: "view-btn",
  },
];

// 待办事项列表数据
const todoList = ref<ISysTodoCenterView[]>([]);

// 路由参数
const routeParams = ref<Record<string, any>>({});

// 筛选表单数据
const filterForm = ref<Record<string, any>>({});

// 处理筛选
const handleFilter = async (filterParams: Record<string, any>) => {
  loading.value = true;
  try {
    // 构建查询参数，映射到API接口需要的字段
    const queryParams: ISysTodoCenterQuery = { Limit: 9999, Page: 1 };

    // 根据筛选参数构建查询对象
    if (filterParams.billCode) {
      queryParams.BillCode = filterParams.billCode;
    }
    if (filterParams.businessType) {
      queryParams.BusinessType = filterParams.businessType;
    }
    if (filterParams.status) {
      queryParams.Status = filterParams.status;
    }
    if (filterParams.priority) {
      queryParams.Priority = filterParams.priority;
    }

    const response = await api.search(queryParams);

    if (response && response.Data) {
      todoList.value = response.Data;
    } else {
      todoList.value = [];
    }
  } catch (error) {
    todoList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "筛选搜索失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 查看待办事项
const handleView = (item: ISysTodoCenterView) => {
  // 检查 MobileRoute 字段
  if (item.MobileRoute && item.MobileRoute.trim() !== "") {
    // 构建跳转参数
    const params: Record<string, string> = {
      id: item.BusinessId || "",
    };

    // 构建查询字符串
    const queryString = Object.keys(params)
      .map((key) => `${key}=${encodeURIComponent(params[key])}`)
      .join("&");

    // 构建完整的跳转路径
    const fullPath = `${item.MobileRoute}?${queryString}`;

    // 执行路由跳转
    uni.navigateTo({
      url: fullPath,
      success: () => {
        console.log(`跳转成功: ${fullPath}`);
      },
      fail: (error) => {
        console.error("跳转失败:", error);
        uni.showToast({
          title: "页面跳转失败",
          icon: "none",
          duration: 2000,
        });
      },
    });
  } else {
    // MobileRoute 为空，显示提示信息
    uni.showToast({
      title: "请到PC端进行审核",
      icon: "none",
      duration: 2000,
    });
  }
};

// 删除待办事项
const handleDelete = async (item: ISysTodoCenterView) => {
  try {
    // 调用删除API
    await api.delete([item.ID!]);

    // 显示成功提示
    uni.showToast({
      title: "删除成功",
      icon: "success",
      duration: 1500,
    });
  } catch (error) {
    // 显示错误提示
    uni.showToast({
      title: "删除失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  }
};

// 处理刷新事件
const handleRefresh = () => {
  // 只有在首次加载或明确需要刷新时才调用fetchData
  if (todoList.value.length === 0) {
    fetchData();
  }
};

// 加载状态
const loading = ref(false);

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const response = await api.search({
      Limit: 9999,
      Page: 1,
    });

    if (response && response.Data) {
      todoList.value = response.Data;
    } else {
      todoList.value = [];
    }
  } catch (error) {
    todoList.value = [];

    // 显示错误提示
    uni.showToast({
      title: "获取待办事项失败，请稍后重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    loading.value = false;
  }
};

// 静默刷新数据获取函数（供XenListPage组件调用）
const silentRefreshFn = async () => {
  const response = await api.search({
    Limit: 9999,
    Page: 1,
  });
  return response?.Data || [];
};

// 处理静默刷新结果
const handleSilentRefresh = (newData: ISysTodoCenterView[]) => {
  todoList.value = newData;
};

// 页面加载时处理路由参数
onLoad((options) => {
  routeParams.value = options || {};

  // 如果有状态参数，设置到筛选表单中
  if (options?.status) {
    filterForm.value.status = options.status;
  }

  // 如果有其他筛选参数，也可以在这里处理
  // 例如：if (options?.priority) filterForm.value.priority = options.priority;
});

// 页面挂载
onMounted(() => {
  // 如果有预设的筛选条件，直接应用筛选；否则获取全部数据
  if (filterForm.value.status) {
    handleFilter(filterForm.value);
  } else {
    fetchData();
  }
});
</script>
